↜ Back to index Introduction to Numerical Analysis 1

Solution Lecture a2

Exercise 3

implicit none
integer a, i

print *, 'Enter a positive integer'
read *, a

do i = 1, 10
    if (mod(a, 2) == 0) then
        a = a / 2
    else
        a = 3 * a + 1
    endif
    print *, a
enddo
end

Exercise 4

implicit none
integer a, i, m

print *, 'Enter a positive integer'
read *, a

m = 0   ! elements of Collatz sequence are positive so 0 is OK
do i = 1, 10
    if (mod(a, 2) == 0) then
        a = a / 2
    else
        a = 3 * a + 1
    endif
    m = max(m, a)
enddo
print *, m
end